package com.hyy.lotterysystem.service.mq;

import com.hyy.lotterysystem.common.utils.JacksonUtil;
import com.hyy.lotterysystem.dao.dataobject.FailedMessageDO;
import com.hyy.lotterysystem.dao.mapper.FailedMessageMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.hyy.lotterysystem.common.config.DirectRabbitConfig.*;

@Component
@RabbitListener(queues = DLX_QUEUE_NAME)
public class DlxConsumer {

    private static final Logger logger = LoggerFactory.getLogger(DlxConsumer.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private FailedMessageMapper failedMessageMapper;

    @RabbitHandler
    public void process(Map<String, String> message) {
        // 死信队列的处理方法
        logger.info("开始处理异常消息！");
        
            // 放入记录错误的表中
            if (message.containsKey("messageData")) {
               saveFailedMessage(message.get("messageData"));
            } else if(message.containsKey("activityID")){
                saveFailedMessage(message.get("activityID"));
            }
    }
    
    /**
     * 保存失败消息到数据库
     * 
     * @param message 消息内容
     */
    private void saveFailedMessage(String message) {

        FailedMessageDO failedMessageDO=new FailedMessageDO(message);
            failedMessageMapper.insert(failedMessageDO);

    }
}
